//  this library.
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:hktk_app/dao/package_dao.dart';
import 'package:hktk_app/exception/dao_exception.dart';
import 'package:hktk_app/model/package/order_model.dart';
import 'package:hktk_app/model/package/package_model.dart';

import 'package:hktk_app/util/buy_ios_util.dart';
import 'package:hktk_app/util/data_util.dart';
import 'package:hktk_app/util/font_util.dart';
import 'package:hktk_app/util/toast_util.dart';
import 'package:hktk_app/util/view_util.dart';

import 'package:hktk_app/widget/package/package_card_widget.dart';
import 'package:hktk_app/widget/package/search_widget.dart';
import 'package:hktk_app/widget/show_label_widget.dart';
import 'package:hktk_app/pages/package/order_payment_page.dart';

/// 购买底部弹出层页面
class PurchaseWidget extends StatefulWidget {
  /// 卡片相关信息
  final PackageModel package;

  /// 当前卡片对应下标
  final int index;

  /// 是否隐藏支付方式（微信/支付宝）,true：隐藏，false：不隐藏
  final bool payHide;

  // 这里暂时隐藏立即支付。避免上架应用宝审核失败。等待审核完成才能进行微信支付
  /// 是否显示联系客服，true：联系客服，false：立即支付。默认为false。
  final bool server;

  const PurchaseWidget({
    super.key,
    required this.package,
    required this.index,
    required this.payHide,
    this.server = false,
  });

  @override
  State<PurchaseWidget> createState() => _PurchaseWidgetState();
}

class _PurchaseWidgetState extends State<PurchaseWidget> {
  late BuildContext _context;

  /// 初始化数据方法
  late Future<Map<String, dynamic>> _futureInit;

  /// 总金额
  late double _totalMoney;

  /// 显示金额
  late double _showMoney;

  /// 套餐相关科目信息
  late List<SkuModel> _skuList;

  /// 搜索关键字
  late String _searchKey;

  @override
  void initState() {
    super.initState();

    _totalMoney = 0;
    _showMoney = 0;
    _searchKey = "";
    _skuList = [];
    _futureInit = _initData();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {

    _context = context;
    // 获取底部安全边距
    double bottom = ScreenUtil().bottomBarHeight;
    return Container(
      padding: EdgeInsets.only(top: 40, bottom: bottom),
      decoration: BoxDecoration(
        color: colorWhite1,
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(30),
          topRight: Radius.circular(30),
        ),
      ),
      child: _futureItem(),
    );
  }

  /// 异步加载方法
  _futureItem() {
    return FutureBuilder<Map<String, dynamic>>(
      future: _futureInit,
      builder: (
          BuildContext context,
          AsyncSnapshot<Map<String, dynamic>> snapshot,
          ) {
        if (snapshot.connectionState == ConnectionState.done) {
          Map<String, dynamic> map = snapshot.data!;
          if (!map["suc"]) {
            WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
              ToastUtil.show(context: _context, msg: map["msg"]);
            });
          }
          return _content();
        } else {
          return const Center(
            child: CircularProgressIndicator(),
          );
        }
      },
    );
  }

  /// 初始化数据方法
  Future<Map<String, dynamic>> _initData() async {
    Map<String, dynamic> map = {};
    try {
      if (widget.package.skuModels == null) {
        _skuList = await PackageDao.packageSkuList(
          packageId: widget.package.id!,
        );
      } else {
        _skuList = widget.package.skuModels!;
        for (SkuModel sku in _skuList) {
          if (sku.isSelect) {
            int price = sku.discountPrice ?? 0;
            double price2 = price / 100;
            _totalMoney = _totalMoney + price2;
            if (widget.payHide) {
              _showMoney = BuyIOSUtil.getIosPrice(_totalMoney);
              break;
            }
          }
        }
        if (!widget.payHide) {
          _showMoney = _totalMoney;
        }
      }
      map["suc"] = true;
    } catch (e) {
      map = {"suc": false, "msg": "未知错误，请重试"};
      if (e is DaoException) {
        map["msg"] = e.msg;
      }
    }
    return map;
  }

  /// 底部金额结算方法
  _bottomMoney() {
    return Container(
      padding: EdgeInsets.symmetric(vertical: 15, horizontal: 32),
      decoration: const BoxDecoration(
          color: colorWhite1,
          boxShadow: [BoxShadow(color: colorBlack4, offset: Offset(0, -1))]),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          SizedBox(
            height: 47,
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.end,
              // textBaseline: TextBaseline.alphabetic,
              children: [
                Text(
                  "合计：",
                  style: FontUtil.fontBlack1(28),
                ),
                Container(
                  padding: EdgeInsets.only(bottom: 4),
                  child: Icon(
                    Icons.currency_yen,
                    size: 26,
                    color: colorOrange6,
                  ),
                ),
                Text(
                  _showMoney.toStringAsFixed(2),
                  style: FontUtil.fontOrange6(36),
                )
              ],
            ),
          ),
          GestureDetector(
            onTap: _onTapFunLjzf,
            child: Container(
              width: 172,
              height: 68,
              decoration: BoxDecoration(
                  color: colorBlue1,
                  borderRadius: BorderRadius.all(Radius.circular(44))),
              child: Center(
                child: Text(
                  widget.server ? "联系客服" : "立即支付",
                  style: FontUtil.fontWhile1(28, fontWeight: FontWeight.w500),
                ),
              ),
            ),
          )
        ],
      ),
    );
  }

  /// 显示卡片
  _card() {
    return Container(
      padding: EdgeInsets.fromLTRB(40, 0, 40, 40),
      decoration: BoxDecoration(
          border: Border(
              bottom: BorderSide(
                color: colorBlack4,
                width: 2,
              ))),
      child: PackageCardWidget(
        isBuy: false,
        package: widget.package,
        index: widget.index,
        payHide: widget.payHide,
      ),
    );
  }

  /// 显示内容
  _content() {
    return Column(
      children: [
        _card(),
        Expanded(
          child: ListView(
            children: [
              _selectedChapter(),
              _addChapter(),
            ],
          ),
        ),
        _bottomMoney(),
      ],
    );
  }

  /// 已选科目
  _selectedChapter() {
    return _chapterContainer([
      Text(
        "已选科目",
        style: FontUtil.fontBlack1(28, fontWeight: FontWeight.w500),
      ),
      hiSpace(height: 24),
      _selectedContent(),
    ]);
  }

  /// 章节边框数据方法
  _chapterContainer(List<Widget> list) {
    return Container(
      margin: EdgeInsets.symmetric(vertical: 40, horizontal: 30),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: list,
      ),
    );
  }

  /// 添加科目
  _addChapter() {
    return _chapterContainer([
      Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            "添加科目",
            style: FontUtil.fontBlack1(28, fontWeight: FontWeight.w500),
          ),
          _searchInput(),
        ],
      ),
      hiSpace(height: 24),
      _addContent(),
    ]);
  }

  /// 搜索输入框
  _searchInput() {
    return SearchWidget(
      onChanged: _searchOnChanged,
    );
  }

  /// 搜索响应内容
  _searchOnChanged(String value) {
    setState(() {
      _searchKey = value;
    });
  }

  /// 已选科目选中显示
  _selectedContent() {
    List<Widget> list = [];
    for (int i = 0; i < _skuList.length; i++) {
      SkuModel sku = _skuList[i];
      if (sku.isSelect && _getSearch(sku.name!)) {
        list.add(ShowLabelWidget.cancel(
          text: sku.name!,
          index: i,
          iconFun: _selectedOnTab,
        ));
      }
    }
    return Wrap(
      // 主轴方向子widget的间距
      spacing: 30,
      // 纵轴方向的间距
      runSpacing: 30,
      children: list,
    );
  }

  /// 取消标签点击响应方法
  _selectedOnTab(int i) {
    // 计算总价格
    int price = _skuList[i].discountPrice ?? 0;
    double price2 = price / 100;
    _totalMoney = _totalMoney - price2;
    // 刷新
    setState(() {
      _skuList[i].isSelect = false;
      if (widget.payHide) {
        _showMoney = BuyIOSUtil.getIosPrice(_totalMoney);
      } else {
        _showMoney = _totalMoney;
      }
    });
  }

  /// 添加科目显示
  _addContent() {
    List<Widget> list = [];
    for (int i = 0; i < _skuList.length; i++) {
      SkuModel sku = _skuList[i];
      if (_getSearch(sku.name!)) {
        list.add(GestureDetector(
          onTap: () {
            _onTapFunAdd(sku, i);
          },
          child: ShowLabelWidget(
            text: sku.name!,
            showIcon: sku.isSelect,
          ),
        ));
      }
    }

    return Wrap(
      // 主轴方向子widget的间距
      spacing: 30,
      // 纵轴方向的间距
      runSpacing: 30,
      children: list,
    );
  }

  /// 添加点击方法
  _onTapFunAdd(SkuModel sku, int index) {
    // 计算总价格
    int price = sku.discountPrice ?? 0;
    double price2 = price / 100;
    if (sku.isSelect == false) {
      // 添加新科目
      if (widget.payHide) {
        // 如果是iOS内购模式，则在有多个选项的时候只允许选择一个
        for (SkuModel sku in _skuList) {
          sku.isSelect = false;
        }
        _totalMoney = 0;
      }
      sku.isSelect = true;
      _totalMoney = _totalMoney + price2;
    } else {
      // 取消选择的科目，直接取消
      sku.isSelect = false;
      _totalMoney = _totalMoney - price2;
    }
    // 刷新
    setState(() {
      _skuList[index] = sku;
      if (widget.payHide) {
        _showMoney = BuyIOSUtil.getIosPrice(_totalMoney);
      } else {
        _showMoney = _totalMoney;
      }
    });
  }

  /// 根据名称判断是否显示
  bool _getSearch(String name) {
    if (_searchKey == "") {
      return true;
    } else {
      return name.contains(_searchKey);
    }
  }

  /// 立即支付点击方法
  _onTapFunLjzf() {

    if (widget.server) {
      // 联系客服，弹框提示
      ToastUtil.showDialogBox(
        context: _context,
        contentText: "请联系客服开通对应科目",
        btnLeftShow: false,
      );
    } else {
      // 立即支付
      _paymentFun();
    }
  }

  /// 立即支付方法
  _paymentFun() {
    List<SkuModel> list = [];
    List<String> list2 = [];
    for (SkuModel sku in _skuList) {
      if (sku.isSelect) {
        list.add(sku);
        list2.add(sku.id!);
      }
    }
    if (list.isNotEmpty) {
      if (dataUtilComm.dataModel.visitorsType) {
        // 跳转登录页面
        // NavigatorUtil.pushToAut2Ret(_context).then((value) {
        //   debugPrint("purchaseWidget 组件 -> 登录页面返回的值 ===> $value");
        //   if (value == true) {
        //     _createOrderFun(list: list, list2: list2);
        //   }
        // });
      } else {
        _createOrderFun(list: list, list2: list2);
      }
    } else {
      ToastUtil.show(context: _context, msg: "请至少选择一个科目！");
    }
  }

  /// 创建订单方法
  _createOrderFun({
    required List<SkuModel> list,
    required List<String> list2,
  }) {
    // 开启加载框
    ToastUtil.loadingBoxShow(_context);
    // 创建订单
    PackageDao.createOrder(skuIds: list2).then((OrderModel orderModel) {

      ToastUtil.loadingBoxRemove();
      // 跳转对应页面
      // NavigatorUtil.push(
      //   _context,
      //   OrderPaymentPage(
      //     price: _totalMoney,
      //     skuList: list,
      //     package: widget.package,
      //     index: widget.index,
      //     orderModel: orderModel,
      //     iosPrice: _showMoney,
      //     payHide: widget.payHide,
      //   ),
      // );
    }).catchError((e) {
      ToastUtil.loadingBoxRemove();
      String str = "未知错误，请重试";
      if (e is DaoException) {
        str = e.msg;
      }
      ToastUtil.show(context: _context, msg: str);
    });
  }
}
